package sample.note;

import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.SneakyThrows;
import sample.note.storage.Repository;

import java.io.*;
import java.util.Map;

import static sample.note.AppWrapper.cheers;

public class ImportActivity extends AppCompatActivity {

    TextView txt;
    Repository repo;
    final Gson gson = new GsonBuilder().create();

    @SneakyThrows
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_export);

        txt = findViewById(R.id.txt);
        repo = new Repository(this);

        input();

    }

    @SneakyThrows
    void input(){
        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            txt.append("External storage Not available.\n");
            return;
        }
        cheers("External available");
        File folder = this.getExternalFilesDir(File.separator);
        if(!folder.exists()){
            cheers("create folder");
            folder.mkdirs();
        }
        File file = new File(folder, this.getPackageName() + ".txt");
        if(!file.exists()){
            txt.append("Not Found.\n");
            return;
        }
        BufferedReader in=new BufferedReader(new FileReader(file));

        String l;
        while((l = in.readLine()) !=null){
            txt.append(l + "\n");
            Map map = gson.fromJson(l, Map.class);
            repo.insertOrUpt(map);
        }

        in.close();
        txt.append("Done!\n");
    }
}
